package com.chancingpack.util;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
 * 
 * @ClassName: CompressUtil 
 * @Description: 将相应的原图压缩成缩略图
 * @author: wu
 * @date: 2017年7月20日 上午8:55:44
 */
public class CompressUtil {

	private Image img;
	private static final int WIDTH = 240;
	private static final int HEIGHT = 240;

	/**
	 * 
	 * @Title:CompressUtil
	 * @Description:构造函数
	 * @param fileName
	 * @throws IOException
	 */
	public CompressUtil(String fileName) throws IOException {
		File file = new File(fileName);// 读入文件
		img = ImageIO.read(file); // 构造Image对象
	}

	/**
	 * 
	 * @Title: resize 
	 * @Description: 强制压缩/放大图片到固定的大小
	 * @param request
	 * @param archId
	 * @throws IOException
	 * @return: void
	 */
	public void resize(HttpServletRequest request, String archId) throws IOException {
		// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		image.getGraphics().drawImage(img, 0, 0, WIDTH, HEIGHT, null); // 绘制缩小后的图
		File destFile = new File(getCompresslPicPath(request) + archId + ".jpg");
		FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
		// 可以正常实现bmp、png、gif转jpg
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		encoder.encode(image); // JPEG编码
		out.close();
	}

	/**
	 * 获取文件的大小
	 * @param f
	 * @return
	 */
	public long getFileLength(File f){
		return f.length();
	}

	/**
	 * 
	 * @Title: getOriginalPicPath
	 * @Description: 获取原图上传存放路径
	 * @param request
	 * @return
	 * @return: String
	 */
	public static String getOriginalPicPath(HttpServletRequest request) {
		return request.getSession().getServletContext().getRealPath("/") + "WEB-INF/resource/upload/original/";
	}

	/**
	 * 
	 * @Title: getCompresslPicPath
	 * @Description: 获取压缩图上传存放路径
	 * @param request
	 * @return
	 * @return: String
	 */
	public static String getCompresslPicPath(HttpServletRequest request) {
		return request.getSession().getServletContext().getRealPath("/") + "WEB-INF/resource/upload/compress/";
	}
}
